package com.afeng.memcached;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import com.afeng.util.log.DltagConstant;
import com.afeng.util.log.LogMessageUtil;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import net.rubyeye.xmemcached.transcoders.SerializingTranscoder;
import net.rubyeye.xmemcached.utils.AddrUtil;

/**
 * 
 * @Title : MemcachedConfig
 * @Description : 初始化MemcachedClient配置类，配置连接池
 * @Date : 2017年11月23日
 * @author : afeng
 */
@Component
public class MemcachedConfig {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(MemcachedConfig.class);

    /**
     * 配置读取加载类
     */
    @Autowired
    MemcachedConfiguration memcachedConfiguration;

    @Bean
    public MemcachedClient initMemcachedClient() {
        
        StringBuffer addresses = new StringBuffer();
        for(String server:memcachedConfiguration.getServers()) {
            addresses.append(server).append(" ");
        }
        
        MemcachedClientBuilder builder = new XMemcachedClientBuilder(
                AddrUtil.getAddresses(addresses.toString().trim()), 
                memcachedConfiguration.getWeights());
        
        builder.setConnectionPoolSize(memcachedConfiguration.getConnectionPoolSize());
        
        // 使用二进制文件  
        builder.setCommandFactory(new BinaryCommandFactory());  
        // 使用一致性哈希算法（Consistent Hash Strategy）  
        builder.setSessionLocator(new KetamaMemcachedSessionLocator());  
        // 使用序列化传输编码  
        builder.setTranscoder(new SerializingTranscoder());  
        // 进行数据压缩，大于1KB时进行压缩  
        builder.getTranscoder().setCompressionThreshold(1024);
        
        MemcachedClient memcachedClient = null;
        try {
            memcachedClient = builder.build();
        } catch (IOException e) {
            
            /*
             * 记录业务日志
             */
            LogMessageUtil logMessageUtil = new LogMessageUtil();
            logMessageUtil.add("msg", "初始化memcache错误。" + e.getMessage());
            logMessageUtil.setDltag(DltagConstant.COM_MYSQL_QUERY_DLTAG);
            LOGGER.error(logMessageUtil.toString(),e);
        }
        return memcachedClient;
    }

}